package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;
import java.util.Random;

import org.apache.http.impl.conn.Wire;
import org.zoolu.sip.header.CSeqHeader;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DTO.RoleDTO;
import com.application.Network.NetworkLayer;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.QuickAction.ActionItem;
import com.application.QuickAction.QuickAction;

import com.application.Tree.BoardView;
import com.application.Tree.BoardViewTN;
import com.application.Tree.TextNode;
import com.application.Tree.TreeNode;
import com.application.outdoor.InvoikeServices.CommonInvoike;
import com.application.outdoor.InvoikeServices.LogThaoTacInvoike;
import com.application.outdoor.InvoikeServices.OperationsInvoike;
import com.application.outdoor.adapter.AvatarAdapter;
import com.application.outdoor.adapter.AvatarEntity;
import com.application.outdoor.adapter.AvatarList;
import com.application.outdoor.adapter.ContactList;
import com.application.outdoor.adapter.GroupEntity;
import com.application.outdoor.pojo.LogUtil;
import com.application.outdoor.pojo.NguoiDungPOJO;

//import com.application.Activity.R;

public class frmTreeNodeActivity extends Activity implements View.OnClickListener {
	/** Called when the activity is first created. */
	public static int ON_EXIT_APP = 1111;
	public static int CODE_KICK = 101;
	public static int CODE_STOP_TALK = 301;
	public static String IP_RESULT = "IP_RESULT";
	public static String USERNAME_RESULT = "USERNAME_RESULT";
	public static Address ipBeingStopTalk;
	int timeStopTalk;
	public static String contentToVote;
	public static int indexOfVote;
	public static int kickVoteResult;
	public static Address ipBeingKick;
	public static int timeVoteKick;
	public static int timeVote;
	public static int timeEstimate;
	ArrayList<CMember> memberList;
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	public static Runnable dislayKickMember;
	public static Runnable dislayKickedMessage;
	public static Runnable raShowMessage;
	public static Runnable raShowToast;
	public static String message;
	public ArrayList<Quyen> quyen = null;
	public static AccountDTO account = null;
	public EditText listChat;
	public EditText txtContent;
	public static Context baseContext;
	public static Handler handler = new Handler();
	public static String ipSender;
	public static String userNameSender;
	public static String userSenderEstimate;
	public static String userSenderVote;
	public static Runnable showFormChatPeer;
	public static Runnable raSignout;
	public static Runnable raStopSession;
	public static Runnable raShowDanhGia;
	public static Runnable raShowBieuQuyet;
	public static Runnable raShowKetQuaBieuQuyet;
	public static String messBieuQuyetResult;
	public static Runnable raShowKetQuaDanhGia;
	static String loi = "";
	String ip = "";
	public static String resultEstimation;
	public static int idindex = 0;
	public static Address Address;
	public static String _title = "";
	// ============SUY NGHI LAI Co NEN DE O DAY
	// KO?????????????====================
	public static Runnable raShowXemLogForm;
	public static Runnable raAddnode = null;
	public static Runnable raAddnodetext = null;
	public static Runnable raUpdateTextNode = null;
	public static Runnable raUpdateNodeText = null;
	public static Runnable raDeleteNode = null;
	public static Runnable raDeleteNodeText = null;
	public static Runnable raResetTree = null;
	LinearLayout layout;
	String value = "";
	public static BoardView board = null;
	private BoardViewTN boardTN;
	LayoutInflater layoutInflater;
	FrameLayout frmLayout;
	LinearLayout llHeader;
	Button btnSwitch, btnSaveTree, btnDeleteAll;
	public static long idNode;
	public static String textUpdate = "";
	public static long id = 0;
	public static TreeNode nodeAdd;
	public static TextNode textnodeAdd;
	public static boolean isActive = false;
	public static int flag;
	private boolean sw = false;
	Button btnZoomOut, btnZoomIn;
	float scale = 1.0f;
	private String userNameResult = "";

	public static long version;
	public static int lb;
	//avatar
	Gallery glAvatar;
	public static Runnable raSetAvatarPosition;
	public static String userNameAvatar="";
	AvatarList lstAvatar=null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_tree_node);
		Log.d("Phu", "frmTreeNodeActivity onCreate");
		isActive = true;
		ArrayList<Quyen> arr = NetworkController._peer.getAccount().getRule();
		NetworkController.beforeKickRule = arr;

		board = (BoardView) findViewById(R.id.boardID);
		boardTN = (BoardViewTN) findViewById(R.id.boardtextID);
		boardTN.setVisibility(View.GONE);

		board.setVisibility(View.VISIBLE);

		// board.readXml(BoardView.treePath);
		// Log.d("Phu", "frmTreeNodeActivity-... đọc file vao nodes :.." +
		// board.getTree().getSumChildren());
		btnZoomIn = (Button) findViewById(R.id.btnZoomIn);
		btnZoomOut = (Button) findViewById(R.id.btnZoomOut);
		btnZoomIn.setOnClickListener(this);
		btnZoomOut.setOnClickListener(this);

		board.isActive = true;
		llHeader = (LinearLayout) findViewById(R.id.llHeader);
		llHeader.setVisibility(View.GONE);

		raAddnode = new Runnable() {
			@Override
			public void run() {
				Log.d("Phu", "frmTreeNodeActivity-raAddnode....board.isActive= " + board.isActive);
				if (board.isActive) {
					Log.d("Phu", "da vao raAddnode roi" + (board == null));
					board.addNode(idNode, nodeAdd, BoardView.treePath);
					board.autoArrange();
				}

			}
		};
		raAddnodetext = new Runnable() {
			@Override
			public void run() {
				if (boardTN.isActive) {
					Log.d("Phu", "frmTreeNodeActivity-raAddnodetext ,kakaka" + (boardTN == null));
					boardTN.addNode(idNode, textnodeAdd, BoardViewTN.treePath);
				}
				boardTN.autoArrange();
			}
		};
		raUpdateTextNode = new Runnable() {
			@Override
			public void run() {
				if (board.isActive) {
					board.updateText(nodeAdd, BoardView.treePath);

				}
			}
		};
		raUpdateNodeText = new Runnable() {
			@Override
			public void run() {
				if (boardTN.isActive)
					boardTN.updateText(textnodeAdd, BoardViewTN.treePath);
			}
		};
		raDeleteNode = new Runnable() {

			@Override
			public void run() {
				Log.d("An", "frmTreeNodeActivity-raDeleteNode... board.isActive= " + board.isActive);
				if (board.isActive) {
					Log.d("An", "frmTreeNodeActivity-raDeleteNode... id= " + nodeAdd.getId());
					board.removeNodeById(nodeAdd, BoardView.treePath);
				}
			}
		};
		raDeleteNodeText = new Runnable() {

			@Override
			public void run() {
				if (boardTN.isActive) {
					Log.d("An", "frmTreeNodeActivity-raDeleteNode Text: idNode= " + nodeAdd.getId());
					boardTN.removeNodeById(textnodeAdd, BoardViewTN.treePath);
				}
			}
		};
		raResetTree = new Runnable() {

			@Override
			public void run() {
				// resetTree();
			}
		};
		dislayKickMember = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				//HienThiMHBieuQuyetKick();
				showNotifyVoteKick();
			}
		};

		dislayKickedMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowMessageKicked();
			}
		};
		showFormChatPeer = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				ShowChatPeerForm(ipSender, userNameSender);
			}
		};

		btnSwitch = (Button) findViewById(R.id.btnSwitch);
		btnSwitch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});

		// ====+TRUC

		raShowMessage = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Show(message);
			}
		};
		raShowToast = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
			}
		};
		// END TRUC========
		// ===an=====
		raSignout = new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Log.d("Phu", "vao 'raSignout'");
				showMessageSignOut(loi);
			}
		};
		// Runalbe raShowDanhGia
		raShowDanhGia = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// Hien thong bao yeu cau nguoi khac Danh gia
				displayNotificationDanhGia();
			}
		};
		raShowBieuQuyet = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// hien thong bao yeu cau Bieu Quyet
				displayNotificationBieuQuyet();
			}
		};
		raShowKetQuaBieuQuyet = new Runnable() {

			@Override
			public void run() {
				//notifyKetQuaBieuQuyet();
				showKetQuaBieuQuyet(messBieuQuyetResult);
			}
		};
		raShowKetQuaDanhGia = new Runnable() {

			@Override
			public void run() {
				notifyKetQuaDanhGia();
			}
		};

		//avatar
		if (NetworkController.isOutDoor()) {
			glAvatar = (Gallery) findViewById(R.id.glAvatar);
			fillAvatar();
		}
		raSetAvatarPosition=new Runnable() {
			
			@Override
			public void run() {
				setPostionAvatar(userNameAvatar);				
			}
		};
		
		raShowXemLogForm=new Runnable() {
			
			@Override
			public void run() {
				if(NetworkController.isInDoor()){
					StartXemLogForm();
				}
				else if(NetworkController.isOutDoor()){
					od_StartXemLogForm();
				}
			}
		};
	}

	public void ShowChatPeerForm(String ipReceiver, String userName) {
		// Intent i = new Intent(this, frmChatPeerActivity.class);
		// startActivity(i);
//		Intent data = new Intent(this, frmChatPeerActivity.class);
//		data.putExtra(frmChatPeerActivity.IP_CHAT_PEER, ipReceiver);
//		data.putExtra(frmChatPeerActivity.USERNAME, userName);
//		setResult(frmChatPeerActivity.CODE_CHATPEER, data);
//
//		startActivity(data);
		
			
			Intent intent = new Intent(this, frmChatPeerActivity.class);
			Bundle ex = new Bundle();
			ex.putInt("ID", 2); 
			
			intent.putExtras(ex);
			intent.putExtra(frmChatPeerActivity.IP_CHAT_PEER, ipReceiver);
			intent.putExtra(frmChatPeerActivity.USERNAME, userName);
			setResult(frmChatPeerActivity.CODE_CHATPEER, intent);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
			NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			Notification notif = new Notification(R.drawable.new_mail, "Có yêu cầu biểu quyết mời thành viên rời nhóm", System.currentTimeMillis());
			notif.setLatestEventInfo(this, "Mời bạn biểu quyết ", "Mời bạn biểu quyết mời thành viên rời nhóm", pendingIntent);
			notif.defaults=Notification.DEFAULT_SOUND;
			notiManager.notify(2, notif);
			Log.d("PEERDROID", "het show notifi kick");
		
	}

	public void showKetQuaBieuQuyet(String message) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		//final EditText input = new EditText(this);
		alert.setTitle("Kết quả biểu quyết");
		//alert.setView(input);
		alert.setIcon(R.drawable.messagebox_info);
		alert.setMessage(message);
		alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});

		alert.show();
	}

	public void ShowMessageKicked() {
		// Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setIcon(R.drawable.messagebox_info)
				.setMessage("Bạn đã bị mời ra khỏi nhóm.")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (NetworkController.isInDoor()) {
							// gửi tin đăng xuất
							NetworkController.SendMessageLogout();
							// thoát khỏi nhóm
							// Thoat();
							// đóng hết form
							NetworkController.EndAllWindow();
						} else if (NetworkController.isOutDoor()) {
							// cập nhật vào csdl xóa người
							// này======?????????????????????????/
							frmTreeNodeActivity.this.finish();
						}
					}
				}).create();
		dlg.show();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btnZoomIn:
			scale += 0.2;
			board.zoom(scale);
			break;
		case R.id.btnZoomOut:
			// scale-=0.2;
			// if(scale<=0.2)
			// scale=0.2f;
			// board.zoom(scale);
			NetworkController.sendVersionTree("192.168.1.88:" + Protocol.PORT, board.treeversion());
			break;
		default:
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		ActivityController.setPeerActivity(this);
		Log.d("Phu", "frmTreeNodeActivity onResume");
		board.readXml(BoardView.treePath);
		board.autoArrange();
		board.isActive = true;
	}

	@Override
	public void onStop() {
		super.onStop();
		isActive = false;
		board.writeXML(BoardView.treePath);
		Log.d("Phu", "frmTreeNodeActivity onStop");
	}

	@Override
	public void onPause() {
		super.onPause();
		isActive = false;

		// isActive=true;
		board.writeXML(BoardView.treePath);
		board.isActive = false;

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("Phu", "frmTreeNodeActivity onDestroy");
	}

	@Override
	public void onStart() {
		super.onStart();
		ActivityController.addActivityToArray(this);
		board.isActive = true;
		isActive = true;
		if (board != null) {
			try {

				board.readXml(BoardView.treePath);
				board.autoArrange();
			} catch (Exception e) {
				Log.d("Phu", "ko doc duoc tree:" + e);
			}
		}
		if (NetworkController._peer == null) {
		
			AccountDTO account = new AccountDTO();
			account.set_Username("quocphu");
			ArrayList<RoleDTO> roleList = ReadWriteFileController.readRole(null, ReadWriteFileController.MY_ROLE_PATH);

			for (RoleDTO role : roleList) {
				account.addRole(role);
				Log.i("Phu", "Role: " + role.getName());
			}
			NetworkController.init("MES", Protocol.PORT, account);

		}

		this.setTitle(NetworkController._peer.getAddressPeer());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// menu.add(Menu.NONE, NOTEPAD, Menu.NONE, "Note")
		// .setIcon(R.drawable.img_clear)
		// .setAlphabeticShortcut('e');
		// menu.add(Menu.NONE, INTERACTION, Menu.NONE, "Cộng tác")
		// .setIcon(R.drawable.img_cauhoi)
		// .setAlphabeticShortcut('f');
		// menu.add(Menu.NONE, SETTING, Menu.NONE, "Tuỳ chỉnh")
		// .setIcon(R.drawable.img_chat)
		// .setAlphabeticShortcut('g');
		// return(super.onCreateOptionsMenu(menu));
		if(NetworkController.isInDoor()){
			new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan_indoor, menu);
		}else if(NetworkController.isOutDoor()){
			new MenuInflater(getApplication()).inflate(R.menu.omnu_thao_luan, menu);
		}
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Phu", " vao ham onActivityResult tree");
		if (resultCode == CODE_KICK) {
			Log.d("Phu", " CODE_KICK");
			String ipKick = data.getStringExtra(IP_RESULT);
			if (ipKick != null) {
				userNameResult = data.getStringExtra(USERNAME_RESULT);
				ShowSetTimeVoteKick(ipKick);

			}
		}
		if (resultCode == CODE_STOP_TALK) {
			Log.d("Phu", " CODE_STOP_TALK");
			String ipStop = data.getStringExtra(IP_RESULT);
			if (ipStop != null) {
				userNameResult = data.getStringExtra(USERNAME_RESULT);
				ShowSetTimeStopTalking(ipStop);
			}
		}
		if (resultCode == ON_EXIT_APP) {
			finish();
		}
	}

	// ============THINKING=====================
	public void HienThiCaiDatThoiGianBieuQuyet() {

		// final EditText txtTime = new EditText(this);
		// txtTime.setSingleLine();
		// txtTime.setInputType(2);
		// AlertDialog dlg = new
		// AlertDialog.Builder(this).setIcon(R.drawable.warning).setTitle("Nhập thời gian biểu quyết")
		// .setMessage("Thời gian được tính bằng giây và nhỏ hơn 1800.").setView(txtTime)
		// .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// String StrTime = txtTime.getText().toString();
		// int time = Integer.parseInt(StrTime);
		// if (time > 1800) {
		// // Show("Thời gian không được lớn hơn 1800 giây.");
		// HienThiCaiDatThoiGianBieuQuyet();
		// } else {
		// timeVote = time;
		//
		// ArrayList<CMember> cmem = ReadWriteFileController
		// .readMember(ReadWriteFileController.MEMBER_PATH);
		// for (int i = 0; i < cmem.size(); i++) {
		// NetworkController.sendGroupBieuQuyet(cmem.get(i).get_ip(),
		// indexOfVote, contentToVote,timeVote);
		// }
		// // Ghi xuống file Log
		// String text = "Đã gởi yêu cầu Biểu Quyết..";
		// // checkIsThanhLapNhom(text);
		// ReadWriteFileController.checkRuleWriteToLogFile(text);
		// // View v=new View(getApplicationContext());
		// // BieuQuyet(v);
		// // dem thoi gian
		// long kickTime = (timeVote * 1000)+2000;
		//
		// CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
		// @Override
		// public void onTick(long millisUntilFinished) {
		//
		// }
		//
		// @Override
		// public void onFinish() {
		// XemBieuQuyet();
		// }
		// }.start();
		// }
		// }
		// }).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
		// {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// // dialog.cancel();
		// }
		// }).create();
		// dlg.show();
	}

	public void XemDanhGia() {
		Intent i = new Intent(this, frmResultDanhGiaActivity.class);
		startActivity(i);

		// ghi xuống file Log
		String text = "Xem kết quả Đánh giá..";
		ReadWriteFileController.checkRuleWriteToLogFile(text);
	}

	public void XemBieuQuyet() {
		frmResultBieuQuyetActivity.indexOfVote = indexOfVote;
		Intent i = new Intent(this, frmResultBieuQuyetActivity.class);
		startActivity(i);

		// ghi xuống file Log
		String text = "Xem Kết quả Biểu Quyết..";
		// WriteToLogFile(text);
		ReadWriteFileController.checkRuleWriteToLogFile(text);
	}

//	public void HienThiMHBieuQuyetKick() {
//		Log.d("Phu", "vao ham HienThiMHBieuQuyetKick");
//		Intent i = new Intent(this.getBaseContext(), frmBieuQuyetMoiRoiNhom.class);
//		startActivity(i);
//	}

	public void HienThiCaiDatThoiGianDanhGia() {
		final EditText txtTime = new EditText(this);
		txtTime.setSingleLine();
		txtTime.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setIcon(R.drawable.messagebox_info)
				.setTitle("Nhập thời gian đánh giá").setMessage("Thời gian được tính bằng giây và nhỏ hơn 1800.")
				.setView(txtTime).setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTime.getText().toString();
						int time = Integer.parseInt(StrTime);
						if (time > 1800) {
							// Show("Thời gian không được lớn hơn 1800 giây.");
							HienThiCaiDatThoiGianDanhGia();
						} else {
							ActivityController.arrayEstimation = new ArrayList<ArrayList<String>>();
							timeEstimate = time;
							DanhGia();
							// dem thoi gian
							long kickTime = (timeEstimate * 1000) + 5000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									//tổng kết đánh giá
//									ArrayList<ArrayList<String>> arrEstResult=new ArrayList<ArrayList<String>>();
									ArrayList<ArrayList<String>> arrActivity=ActivityController.arrayEstimation;
									Log.i("Phu", "estima arr size = "+arrActivity.size());
									String result="";
									float sum, mean;
									int countEst=NetworkController.countEstimation;
									for(int i=0;i<arrActivity.size();i++){//duyệt từng thành viên
										float rating=0;
										ArrayList<String> arrUser=arrActivity.get(i);
										//ActivityController.arrayEstimation.get(i);//thành viên thứ 1
										//ActivityController.arrayEstimation.get(i).get(0);//username của thành viên thứ 1
//										arrUser.add(arrActivity.get(i).get(0));//username của thành viên thứ i
										sum=Float.parseFloat(arrUser.get(1));
										mean=sum/countEst;
										rating=(mean/10)*100;
										Log.w("Phu", "rating float="+rating);
//										arrUser.add(Math.round(rating)+"");
//										arrEstResult.add(arrUser);
										result+=arrActivity.get(i).get(0)+"/"+Math.round(rating)+";";
										Log.i("Phu", "rating result = "+result);
									}
									
									
									if (NetworkController.isOutDoor()) {
										try {
											new OperationsInvoike().SendResultDanhGia(CommonUtilities.nguoiDung
													.getTenDangNhap(),result);
										} catch (Exception e) {
											Log.d("Phu", "Không thể gửi kết quả đánh giá.");
										}

									} else if (NetworkController.isInDoor()) {
										NetworkController.GuiKetQuaDanhGia(result);
									}
									// ghi xuống file Log
									String text = "Gửi Kết quả đánh giá..";
									// WriteToLogFile(text);
									ReadWriteFileController.checkRuleWriteToLogFile(text);
								}
							}.start();
						}
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// dialog.cancel();
					}
				}).create();
		dlg.show();
	}

	public void ShowSetTimeVoteKick(final String IP) {

		Log.d("Phu", " vao ShowSetTimeVoteKick");
		Log.d("Phu", "ip kick" + IP);
		Log.d("Phu", "My ip " + NetworkController._peer.getAddressPeer());

		final EditText txtTime = new EditText(this);
		txtTime.setSingleLine();
		txtTime.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setIcon(R.drawable.messagebox_info)
				.setTitle("Nhập thời gian biểu quyết").setMessage("Thời gian được tính bằng giây và nhỏ hơn 1800.")
				.setView(txtTime).setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						String StrTime = txtTime.getText().toString();
						int time = Integer.parseInt(StrTime);
						if (StrTime.equals("") || time > 1800) {
							// Show("Thời gian không được lớn hơn 1800 giây.");
							ShowSetTimeVoteKick(IP);
						} else {
							timeVoteKick = time;
							yesVote = new ArrayList<Integer>();
							noVote = new ArrayList<Integer>();
							// memberList =
							// ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
							// for (CMember member : memberList) {
							// NetworkController.SendVoteKickMember(new
							// Address(member.get_ip()), ipBeingKick, time);
							// }
							if (NetworkController.isInDoor()) {
								ipBeingKick = new Address(IP);
								NetworkController.SendVoteKickMemberGroup(userNameResult, ipBeingKick, time);
							} else if (NetworkController.isOutDoor()) {
								// gửi bang outdoor
								try {
									new OperationsInvoike().SendVoteKickMember(userNameResult,
											CommonUtilities.nguoiDung.getTenDangNhap(), time);
								} catch (Exception e) {
									Log.d(Protocol.TAG, "Không thể gửi yêu cầu kick " + e.getMessage());
								}
							}
							Log.d("Phu", "Da gui xong kick");
							// dem thoi gian
							long kickTime = timeVoteKick * 1000+5000;

							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									// Toast.makeText(getBaseContext(),
									// "het gio kick",
									// Toast.LENGTH_SHORT).show();
									Log.v("Phu", "yes size=null " + (yesVote==null));
									Log.v("Phu", "no size= null " + (noVote==null));
									Log.w("Phu", "yes size=" + yesVote.size());
									Log.w("Phu", "no size=" + noVote.size());
									kickVoteResult = 0;
									if (yesVote.size() != 0 || noVote.size() != 0) {

										if (yesVote.size() >= noVote.size()) {
											kickVoteResult = 1;
										}

									} else {
										// NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
										NetworkController.ShowMessageNoticeOnTree("Không có ai tham gia biểu quyết.");
									}
									if (NetworkController.isInDoor()) {
										memberList = ReadWriteFileController
												.readMember(ReadWriteFileController.MEMBER_PATH);
										for (CMember member : memberList) {
											Log.d("Phu", "gui result toi " + member.get_ip());
											NetworkController.SendResultVoteKickMember(new Address(ipBeingKick),
													kickVoteResult, ipBeingKick, userNameResult);
										}
									} else if (NetworkController.isOutDoor()) {
										try {
											new OperationsInvoike().SendResultVoteKickMember(
													CommonUtilities.nguoiDung.getTenDangNhap(), kickVoteResult,
													userNameResult);
										} catch (Exception e) {
											Log.d(Protocol.TAG, "Không thể gửi kết quả của kick " + e.getMessage());
										}
									}
								}
							}.start();
						}
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// dialog.cancel();
					}
				}).create();
		dlg.show();

	}

	public void ShowSetTimeStopTalking(final String ipStop) {

		final EditText txtTimeTalk = new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg = new AlertDialog.Builder(this).setIcon(R.drawable.messagebox_info)
				.setTitle("Nhập thời gian buộc ngừng thảo luận")
				.setMessage("Thời gian được tính bằng giây và nhỏ hơn 18000.").setView(txtTimeTalk)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String StrTime = txtTimeTalk.getText().toString();

						int time = Integer.parseInt(StrTime);
						if (StrTime.equals("") || time > 1800) {
							// Show("Thời gian không được lớn hơn 18000 giây.");
							ShowSetTimeStopTalking(ipStop);
						} else {
							String NguoiNhan = userNameResult;
							timeStopTalk = time;
							if (NetworkController.isInDoor()) {
								ipBeingStopTalk = new Address(ipStop);
								NetworkController.GuiYeuCauNgungThaoLuan(ipBeingStopTalk, time);
								Log.d("Phu", "vao onclick ngung noi");
							} else if (NetworkController.isOutDoor()) {
								try {
									new OperationsInvoike().SendStopTalkMember(
											CommonUtilities.nguoiDung.getTenDangNhap(), time, NguoiNhan);
								} catch (Exception e) {
									Log.d(Protocol.TAG, "Không thể gửi yêu cầu ngung thao luan " + e.getMessage());
								}
							}
							long timeLong = timeStopTalk * 1000;
							// Toast.makeText(getBaseContext(), timeLong + "",
							// 1).show();
							CountDownTimer timer = new CountDownTimer(timeLong, 1000) {

								@Override
								public void onTick(long millisUntilFinished) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onFinish() {
									// TODO Auto-generated method stub
									if (NetworkController.isInDoor())
										NetworkController.GuiChoPhepThaoLuan(ipBeingStopTalk);
									else if (NetworkController.isOutDoor()) {
										try {
											new OperationsInvoike().SendAcceptTalkMember(
													CommonUtilities.nguoiDung.getTenDangNhap(), userNameResult);
										} catch (Exception e) {
											Log.d(Protocol.TAG, "Không thể gửi cho phep thao luan " + e.getMessage());
										}
									}
								}
							}.start();
						}
					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).create();
		dlg.show();

	}

	// //=======END THINKING====================
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (NetworkController._statusLogin != Protocol.IS_ONLINE_OUTDOOR) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setIcon(R.drawable.img_dialog);
				builder.setMessage("Bạn có chắc muốn rời khỏi nhóm hiện tại ?").setCancelable(false)
						.setIcon(R.drawable.messagebox_warning)
						.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								if (NetworkController._peer.getAccount().isThanhLapNhom) {
									NetworkController._peer.getAccount().isThanhLapNhom = false;
								}
								Thoat();
							}
						}).setNegativeButton("No", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// switch (item.getItemId()) {
		// case NOTEPAD:
		// startActivity(new Intent(this, FrmNote.class));
		// return(true);
		// case INTERACTION:
		// startActivity(new Intent(this, FrmInteraction.class));
		// return(true);
		// case SETTING:
		// startActivity(new Intent(this, PrefSetting.class));
		// return(true);
		// }

		// return super.onOptionsItemSelected(item);

		int id = item.getItemId();

		switch (id) {
		case R.id.mnuDanhSachThanhVien:
			Intent iDanhSachThanhVien = new Intent(getBaseContext(), frmDanhSachThanhVienActivity.class);
			startActivityForResult(iDanhSachThanhVien, CODE_KICK);
			break;
		case R.id.mnuChiaSeTaiLieu:
			// Chia sẻ tài liệu
			if (NetworkController.isOutDoor()) {
				od_ShareFileActivity.idNhom = CommonUtilities.idNhomHienTai;
				Intent iShareFile = new Intent(frmTreeNodeActivity.this, od_ShareFileActivity.class);
				startActivity(iShareFile);
			}
			break;
		case R.id.mnuVaoTroCuaToi:
			Intent iVaiTro = new Intent(getBaseContext(), frmVaiTroCuaToiActivity.class);
			startActivity(iVaiTro);
			break;
		case R.id.mnuQuyenCuaToi:
			Intent iQuyen = new Intent(getBaseContext(), frmQuyenCuaToi.class);
			startActivity(iQuyen);
			break;
		case R.id.mnuBieuQuyet:
			// Intent iBieuQuyet = new Intent(getBaseContext(),
			// frmBieuQuyetActivity.class);
			// startActivity(iBieuQuyet);
			
			Quyen quyen = NetworkController._peer.getAccount().getRuleById(Protocol.R_YEU_CAU_BIEU_QUYET);
			if (quyen != null && quyen.getSend()) {

				View v = new View(getApplicationContext());
				BieuQuyet(v);
				// HienThiCaiDatThoiGianBieuQuyet();
				
				//Ghi log
				if(NetworkController.isInDoor()){
					ReadWriteFileController.WriteToLogFile("Tạo biểu quyết");
				}else if(NetworkController.isOutDoor()){
					//Ghi log
					new LogThaoTacInvoike().insert(CommonUtilities.nguoiDung.getTenDangNhap(),"true", CommonUtilities.idCayHienTai, LogUtil.TAO_BIEU_QUYET);
				}
			} else{
				NetworkController.ShowMessageNoticeOnTree(Protocol.NON_RULE_MESSAGE);
				//Ghi log
				if(NetworkController.isInDoor()){
					ReadWriteFileController.WriteToLogFile("Không có quyền Tạo biểu quyết");
				}else if(NetworkController.isOutDoor()){
					//Ghi log
					new LogThaoTacInvoike().insert(CommonUtilities.nguoiDung.getTenDangNhap(),"Không có quyền Tạo biểu quyết", CommonUtilities.idCayHienTai, LogUtil.TAO_BIEU_QUYET);
				}
			}
			break;
		case R.id.mnuDanhGia:
			// Intent iDanhGia = new Intent(getBaseContext(),
			// frmDanhGiaActivity.class);
			// startActivity(iDanhGia);
			Quyen q = NetworkController._peer.getAccount().getRuleById(Protocol.R_YEU_CAU_DANH_GIA);
			if (q != null && q.getSend()){
				// showDanhGiaQuestion();
				HienThiCaiDatThoiGianDanhGia();
				//Ghi log
				if(NetworkController.isInDoor()){
					ReadWriteFileController.WriteToLogFile("Tạo đánh giá");
				}else if(NetworkController.isOutDoor()){
					//Ghi log
					new LogThaoTacInvoike().insert(CommonUtilities.nguoiDung.getTenDangNhap(),"true", CommonUtilities.idCayHienTai, LogUtil.DANH_GIA);
				}
			}
			else{
				NetworkController.ShowMessageNoticeOnTree(Protocol.NON_RULE_MESSAGE);
			// DanhGia();
				//Ghi log
				if(NetworkController.isInDoor()){
					ReadWriteFileController.WriteToLogFile("Không có quyền Tạo đánh giá");
				}else if(NetworkController.isOutDoor()){
					//Ghi log
					new LogThaoTacInvoike().insert(CommonUtilities.nguoiDung.getTenDangNhap(),LogUtil.NONE_RULE, CommonUtilities.idCayHienTai, LogUtil.TAO_BIEU_QUYET);
				}
			}
			break;
		case R.id.mnuThoat:
			Thoat();
			break;
		case R.id.mnuXemLog:			
			if(NetworkController.isInDoor()){
				NetworkController.showXemLogForm();
			}
			else if(NetworkController.isOutDoor()){
				od_LogThaoTacAcivity.idCay=CommonUtilities.idCayHienTai;
				Intent iLog=new Intent(getBaseContext(), od_LogThaoTacAcivity.class);
				startActivity(iLog);
			}
			break;
//		case R.id.mnuDungThaoLuan:
//			DungThaoLuan();
//			break;
		default:
			break;
		}
		return true;
	}

	public void XemLog() {
		//
	}

	void StartXemLogForm(){
		Intent i = new Intent(this, frmViewLogFile.class);
		startActivity(i);
	}
	void od_StartXemLogForm(){
		Intent i = new Intent(this, od_LogThaoTacAcivity.class);
		startActivity(i);
	}
	public void DungThaoLuan() {
		Quyen q = NetworkController._peer.getAccount().getRuleById(Protocol.R_DUNG_CUOC_HOP);
		if (q != null && q.getSend()) {
			// board.getTree().clearChildren();
			// Log.d("An", "getSumChildren: " +
			// board.getTree().getSumChildren());
			// board.stopDiscuss = true;
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			// EditText time = new EditText(this);
			// dialog.setView(time);
			dialog.setTitle("Bạn có chắc muốn Dừng Thảo Luận");
			dialog.setIcon(R.drawable.messagebox_warning);
			dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					board.getTree().clearChildren();
					if (NetworkController.isInDoor()) {
						// Gửi thông tin cho các thành viên
						ArrayList<CMember> members = ReadWriteFileController
								.readMember(ReadWriteFileController.MEMBER_PATH);
						for (CMember m : members) {
							}
						}
						// gửi xong thì xóa cây của mình
						NetworkController.receiveClearNode();
					}
				}
			).setNegativeButton("No", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.cancel();
				}
			});
			dialog.show();

		} else {
			MESApplication.showDialog(this, "Thông báo", "Bạn không có quyền này.");
		}
	}

	public static void thongBaoDungThaoLuan(Context c) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(c);
		dialog.setTitle("Dừng Thảo Luận");
		dialog.setIcon(R.drawable.messagebox_info);
		dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				board.getTree().clearChildren();

			}
		});
		dialog.show();
	}

	public void Thoat() {
		ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
		for (int i = 0; i < cmem.size(); i++) {
			String name = String.valueOf(NetworkController._peer.getAccount().get_Username());
			Log.d("PEERDROID", "fullname: " + name);
			NetworkController.sendGroupSignOut(cmem.get(i).get_ip(), name);
		}
		NetworkController._peer.getAccount().setInGroup(false);
		// ghi xuống file Log
		String text = "Đã rời khỏi nhóm..";
		ReadWriteFileController.checkRuleWriteToLogFile(text);
		NetworkController._peer.amountMemberGroup = 0;
		// NetworkController._peer.getAccount().isThanhLapNhom=false;
		finish();
	}

	public void DanhGia() {
		Log.v("Phu", "vao ham danh gia");
		// Quyen quyen = NetworkController._peer.getAccount().getRuleById(19);
		// Log.d("PEERDROID", "Quyen send Đánh giá = " + quyen.getSend());
		// if (quyen != null && quyen.getSend()) {
		if (NetworkController.isInDoor()) {
			ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
			for (int i = 0; i < cmem.size(); i++) {
				Log.d("PEERDROID", "IP memberlist: " + String.valueOf(cmem.get(i).get_ip()));
				NetworkController.sendGroupDanhGia(cmem.get(i).get_ip());
				// NetworkController.sendGroupDanhGia("192.168.1.99:" + port);
			}
		} else if (NetworkController.isOutDoor()) {
			try {
				Log.i("Phu", "nguoi gui=" + CommonUtilities.nguoiDung.getTenDangNhap());
				new OperationsInvoike().SendDanhGia(CommonUtilities.nguoiDung.getTenDangNhap());
			} catch (Exception e) {
				Log.d("Phu", "Không thể gửi yêu cầu đánh giá.");
			}
		}
		// ghi xuống file Log
		String text = "Gởi yêu cầu Đánh giá..";
		ReadWriteFileController.checkRuleWriteToLogFile(text);
		// } else {
		// Show(Protocol.NON_RULE_MESSAGE);
		// }
	}

	public void Show(String message) {

		AlertDialog dlg = new AlertDialog.Builder(this).setCancelable(true).setIcon(R.drawable.messagebox_info)
				.setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}

	public void BieuQuyet(View v) {
		// Các khai báo QuickAction
		// vote100accept action item
		ActionItem vote100accept = new ActionItem();
 
		vote100accept.setTitle("100% Accept");
		vote100accept.setIcon(getResources().getDrawable(R.drawable.add_vote_choose));

		// vote75accept action item
		ActionItem vote75accept = new ActionItem();

		vote75accept.setTitle("75% Accept");
		vote75accept.setIcon(getResources().getDrawable(R.drawable.ic_accept));

		// vote50accept action item
		ActionItem vote50accept = new ActionItem();

		vote50accept.setTitle("50% Accept");
		vote50accept.setIcon(getResources().getDrawable(R.drawable.ic_up));

		final QuickAction mQuickAction = new QuickAction(this);
		// add QuickAction
		mQuickAction.addActionItem(vote100accept);
		mQuickAction.addActionItem(vote75accept);
		mQuickAction.addActionItem(vote50accept);
		
		// setup the action item click listener
		mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
			@Override
			public void onItemClick(int pos) {
				int percent=0;
				if (pos == 0) { // Add item selected
					percent=100;
					indexOfVote = 1;
					showDialogQuickAction(1);
				} else if (pos == 1) { // Accept item selected
					percent=75;
					indexOfVote = 2;
					showDialogQuickAction(2);
				} else if (pos == 2) { // Upload item selected
					percent=50;
					indexOfVote = 3;
					showDialogQuickAction(3);
				}
				// Ghi xuống file Log
				String text = "Đã chọn phần trăm biểu quyết là "+percent+" %"; 
				// checkIsThanhLapNhom(text);
				ReadWriteFileController.checkRuleWriteToLogFile(text);
			}
		});
		// Quyen quyen = NetworkController._peer.getAccount().getRuleById(18);
		// Log.d("PEERDROID","Quyen send = " + quyen.getSend());
		// if (quyen != null && quyen.getSend()) {
		mQuickAction.show(v);
		mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
		// }else{
		// Log.d("PEERDROID","ko co quyen send bieu quyet ");
		// Show(Protocol.NON_RULE_MESSAGE);
		// }

	}

	// Hàm Show Dialog khi click chọn QuickAction
	public void showDialogQuickAction(final int index) {
		Log.v("Phu", "show index of vote=" + indexOfVote);
		final EditText txtTitle = new EditText(this);
		final TextView tvMess=new TextView(getBaseContext());
		tvMess.setText("Nhập vấn đề cần biểu quyết");
		tvMess.setTextSize(15);
		txtTitle.setInputType(1);
		final EditText txtTime = new EditText(this);
		txtTime.setSingleLine();
		txtTime.setInputType(2);
		final TextView tvTime = new TextView(getBaseContext());
		tvTime.setText("Nhập thời gian.\nThời gian được tính bằng giây và nhỏ hơn 1800");
		ScrollView scroll=new ScrollView(getApplicationContext());
		LinearLayout layout = new LinearLayout(getBaseContext());
		layout.setOrientation(1);
		layout.addView(tvMess);
		layout.addView(txtTitle);
		layout.addView(tvTime);
		layout.addView(txtTime);
		scroll.addView(layout);
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("Yêu Cầu Biểu Quyết").setIcon(R.drawable.messagebox_info)//.setMessage("Nhập vấn đề cần biểu quyết")
				.setView(scroll)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						ActivityController._count = 0;
						ActivityController._valueAgree = 0;
						ActivityController._valueDisAgree = 0;
						contentToVote = txtTitle.getText().toString();
						indexOfVote = index;
						String StrTime = txtTime.getText().toString();
						int time = Integer.parseInt(StrTime);
						if (StrTime.equals("") || time > 1800) {
							// Show("Thời gian không được lớn hơn 1800 giây.");
							// HienThiCaiDatThoiGianBieuQuyet();
							showDialogQuickAction(index);
						} else {
							timeVote = time;
							if (NetworkController.isInDoor()) {
								ArrayList<CMember> cmem = ReadWriteFileController
										.readMember(ReadWriteFileController.MEMBER_PATH);
								for (int i = 0; i < cmem.size(); i++) {
									NetworkController.sendGroupBieuQuyet(cmem.get(i).get_ip(), indexOfVote,
											contentToVote, timeVote);
								}
								// Ghi xuống file Log
								String text = "Đã gởi yêu cầu Biểu Quyết..";
								// checkIsThanhLapNhom(text);
								ReadWriteFileController.checkRuleWriteToLogFile(text);
							} else if (NetworkController.isOutDoor()) {
								try {
									
									Log.i("Phu", "nguoi gui=" + CommonUtilities.nguoiDung.getTenDangNhap());

									new OperationsInvoike().SendBieuQuyet(CommonUtilities.nguoiDung.getTenDangNhap(),
											contentToVote, timeVote);
								} catch (Exception e) {
									Log.d("Phu", "Không thể gửi yêu cầu biểu quyết.");
								}
							}
							// View v=new View(getApplicationContext());
							// BieuQuyet(v);
							// dem thoi gian
							long kickTime = (timeVote * 1000) + 10000;// trừ hao
																		// 10s
																		// để
																		// các
																		// thành
																		// viên
																		// khác
																		// chạy
							
							CountDownTimer timer = new CountDownTimer(kickTime, 1000) {
								@Override
								public void onTick(long millisUntilFinished) {

								}

								@Override
								public void onFinish() {
									// XemBieuQuyet();
									int agr=ActivityController._valueAgree;
									int disAgree=ActivityController._valueDisAgree;
									int kq=0;
									int tongVote=agr+disAgree;
									int tongThanhVien=NetworkLayer.amountMemberGroup;
									int agree=(tongThanhVien-tongVote)+agr;
									float YesV=0;
									float NoV=0;
									float Yes=0;
									float No=0;
									Log.v("Phu","kq="+kq);
									Log.v("Phu","index Of vote="+indexOfVote);
									if(indexOfVote==1){//100%
										
										YesV=(Float.parseFloat(agree+"")*100)/tongThanhVien;
										NoV=(Float.parseFloat(disAgree+"")*100)/tongThanhVien;
										if(YesV==100){
											kq=1;
										}
										//else kq=0
									}
									else if(indexOfVote==2){//75%
										YesV=(Float.parseFloat(agree+"")*75)/tongThanhVien;
										NoV=(Float.parseFloat(disAgree+"")*75)/tongThanhVien;
										if(YesV>=75){
											kq=1;
										}
										//else kq=0
									}
									else if(indexOfVote==3){//50%
										YesV=(Float.parseFloat(agree+"")*50)/tongThanhVien;
										NoV=(Float.parseFloat(disAgree+"")*50)/tongThanhVien;
										if(YesV>=50){
											kq=1;
										}
										//else kq=0
									}
									Log.v("Phu","Yes="+YesV);
									Log.v("Phu","No="+NoV);
//									if(Yes>=No){
//										kq=1;
//									}
									Log.v("Phu","final kq="+kq);
									if (NetworkController.isOutDoor()) {
										try {
											new OperationsInvoike().SendResultBieuQuyet(CommonUtilities.nguoiDung
													.getTenDangNhap(),kq,contentToVote);
										} catch (Exception e) {
											Log.d("Phu", "Không thể gửi kết quả biểu quyết.");
										}
										// ghi xuống file Log

									} else if (NetworkController.isInDoor()) {
										
										NetworkController.GuiKetQuaBieuQuyet(indexOfVote,kq,contentToVote);
										String text = "Gửi Kết quả Biểu Quyết.Kết quả là "+(kq==1?"Thông qua":"Bác bỏ");
										// WriteToLogFile(text);
										ReadWriteFileController.checkRuleWriteToLogFile(text);
									}
									
									
								}
							}.start();
						}

					}
				}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				}).create();
		dialog.show();
	}

	public static void showSignOut(String name) {
		loi = name + " đã rời khỏi nhóm.";
		Log.d("PEERDROID", "name sign out: " + loi);
		handler.post(raSignout);

	}

	// public void showDanhGiaQuestion() {
	// AlertDialog dlg = new
	// AlertDialog.Builder(this).setTitle("Thông báo").setIcon(R.drawable.warning)
	// .setMessage("Bạn thật sự muốn gửi yêu cầu đánh giá?")
	// .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// DanhGia();
	// }
	// }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// // TODO Auto-generated method stub
	// dialog.cancel();
	// }
	// }).create();
	// dlg.show();
	// }

	public void showMessageSignOut(String name) {
		Log.d("PEERDROID", "vao day");
		Toast.makeText(this, name + " da roi nhom", Toast.LENGTH_SHORT).show();
	}

	public void displayNotificationDanhGia() {
		frmDanhGiaActivity.userSender = userSenderEstimate;
		Intent intent = new Intent(getApplicationContext(), frmDanhGiaActivity.class);
		Log.i("Phu","qua khoi tao Intent");
		intent.putExtra("ID", 1);
		intent.putExtra("SENDER", Address.toString());
		Log.i("Phu","qua Intent rui");
	
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.new_mail, "Có yêu cầu đánh giá", System.currentTimeMillis());
		
		Log.i("Phu","vao Pending Intent ");
		notif.setLatestEventInfo(this,"Có yêu cầu đánh giá ", "Mời đánh giá", pendingIntent);
		notif.flags|=Notification.FLAG_AUTO_CANCEL;
		notif.when=1;
		notif.defaults=Notification.DEFAULT_SOUND;
		notiManager.notify(1, notif);
//		Intent intent = new Intent(this, frmDanhGiaActivity.class);
//		Bundle ex = new Bundle();
//		ex.putInt("ID", 2);
//		ex.putString("SENDER", String.valueOf(Address));
//		intent.putExtras(ex);
//		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//		Notification notif = new Notification(R.drawable.new_mail, "Có yêu cầu đánh giá", System.currentTimeMillis());
//		notif.setLatestEventInfo(this, "Có yêu cầu đánh giá ", "Mời đánh giá", pendingIntent);
//
//		notiManager.notify(2, notif);
		
		Log.d("PEERDROID", "het show notifi danh gia");
		
	}

	public void displayNotificationBieuQuyet() {
		frmBieuQuyetActivity.userSender = userSenderVote;
		frmBieuQuyetActivity.contentVote = contentToVote;
		frmBieuQuyetActivity.timeVote = timeVote;
		
		Intent intent = new Intent(this, frmBieuQuyetActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 3);
		ex.putInt("INDEX", idindex);
		ex.putString("SENDER", String.valueOf(Address));
		ex.putString("TITLE", _title);
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.new_mail, "Có yêu cầu biểu quyết", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Mời bạn biểu quyết ", "Mời biểu quyết", pendingIntent);
		notif.defaults=Notification.DEFAULT_SOUND;
		notiManager.notify(3, notif);
		Log.d("PEERDROID", "het show notifi bieu quyet");
	}

	public void notifyKetQuaBieuQuyet() {
		frmResultBieuQuyetActivity.indexOfVote = indexOfVote;
		Intent intent = new Intent(this, frmResultBieuQuyetActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 1);
		ex.putInt("INDEX", idindex);
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.new_mail, "Có kết quả biểu quyết", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Mời bạn xem kết quả biểu quyết ", "Xem kết quả biểu quyết", pendingIntent);

		notiManager.notify(1, notif);
		notif.defaults=Notification.DEFAULT_SOUND;
		Log.d("PEERDROID", "het show notifi KQ bieu quyet");
	}

	public void notifyKetQuaDanhGia() {
		frmResultDanhGiaActivity.ResultEstimation=resultEstimation;
		Intent intent = new Intent(this, frmResultDanhGiaActivity.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 2); 
		
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.new_mail, "Có kết quả đánh giá", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Mời bạn xem kết quả đánh giá ", "Xem kết quả đánh giá", pendingIntent);
		notif.defaults=Notification.DEFAULT_SOUND;
		notiManager.notify(2, notif);
		Log.d("PEERDROID", "het show notifi KQ đánh giá");
	}
// public static void showNotificationBieuQuyet(int index, Address sender,
	// String title) {
	// Log.d("PEERDROID", " da vao shownotifi......");
	// idindex = index;
	// Address = sender;
	// _title = title;
	// // Log.d("PEERDROID", "vao frm truc" + String.valueOf(index) +
	// // String.valueOf(sender));
	// handler.post(raShowBieuQuyet);
	// }

	// public static void showRequestDanhGia(Address sender) {
	// Log.d("PEERDROID", " da vao shownotifi......");
	// Address = sender;
	// Log.d("PEERDROID", "vao frm truc" + String.valueOf(sender));
	// handler.post(raShowDanhGia);
	// }

	private void fillAvatar(){
		ArrayList<NguoiDungPOJO> lstNguoiDung=CommonUtilities.contacts.getNguoiTrongNhom(CommonUtilities.idNhomHienTai);
		
		 lstAvatar=new AvatarList();
		for(int i=0;i<lstNguoiDung.size();i++){
			AvatarEntity avatar=new AvatarEntity(lstNguoiDung.get(i).getTenDangNhap(), this);
			lstAvatar.add(avatar);
		}
		AvatarAdapter adapter=new AvatarAdapter(this, lstAvatar);
		glAvatar.setAdapter(adapter);
	}
	private void setPostionAvatar(String userName){
		try{
		int index=lstAvatar.getIndex(userName);
		glAvatar.setSelection(index, true);
		}catch (Exception e){
			Log.e(Protocol.TAG,"frmTreeNodeActivity.setPostionAvatar"+e.getMessage());
		}
	}
	public void showNotifyVoteKick() {
		
		Intent intent = new Intent(this, frmBieuQuyetMoiRoiNhom.class);
		Bundle ex = new Bundle();
		ex.putInt("ID", 2); 
		
		intent.putExtras(ex);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.new_mail, "Có yêu cầu biểu quyết mời thành viên rời nhóm", System.currentTimeMillis());
		notif.setLatestEventInfo(this, "Mời bạn biểu quyết ", "Mời bạn biểu quyết mời thành viên rời nhóm", pendingIntent);
		notif.defaults=Notification.DEFAULT_SOUND;
		notiManager.notify(2, notif);
		Log.d("PEERDROID", "het show notifi kick");
	}
}